<template>
  <div class="login-container">
    <el-card class="login-card">
      <div class="login-header">
        <img src="@/assets/logo.png" alt="logo" class="logo">
        <h2>医键三连</h2>
      </div>

      <!-- 添加身份选择 -->
      <div class="role-select">
        <el-radio-group v-model="selectedRole" size="large">
          <el-radio-button value="user">我是用户</el-radio-button>
          <el-radio-button value="nurse">我是陪诊师</el-radio-button>
        </el-radio-group>
      </div>

      <el-form
        :model="loginForm"
        :rules="rules"
        ref="loginFormRef"
        class="login-form">
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            :placeholder="rolePlaceholder"
            prefix-icon="User">
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="密码"
            prefix-icon="Lock"
            show-password>
          </el-input>
        </el-form-item>

        <div class="login-options">
          <el-checkbox v-model="rememberMe">记住我</el-checkbox>
          <div class="right-options">
            <el-link
              type="primary"
              @click="goToRegister">
              注册账号
            </el-link>
            <el-divider direction="vertical" />
            <el-link type="primary">忘记密码？</el-link>
          </div>
        </div>

        <el-button
          type="primary"
          class="login-button"
          :loading="loading"
          @click="handleLogin">
          登录
        </el-button>

        <!-- 仅用户端显示人脸识别登录 -->
        <div class="face-login">
          <el-divider>其他登录方式</el-divider>
          <el-button
            type="success"
            plain
            icon="Camera"
            @click="startFaceAuth">
            {{ selectedRole === 'user' ? '人脸识别登录' : '人脸验证登录' }}
          </el-button>
        </div>
      </el-form>

      <!-- 新增人脸采集入口 -->
      <div class="face-collection">
        <el-button
          type="primary"
          @click="showFaceCollection = true">
          人脸采集
        </el-button>
      </div>
    </el-card>

    <!-- 新增人脸采集对话框 -->
    <el-dialog
      v-model="showFaceCollection"
      title="人脸采集"
      width="400px"
      center>
      <el-form
        :model="faceCollectionForm"
        :rules="faceCollectionRules"
        ref="faceCollectionFormRef"
        label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="faceCollectionForm.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="faceCollectionForm.password" type="password" />
        </el-form-item>
        <el-form-item label="身份" prop="role">
          <el-radio-group v-model="selectedRole">
            <el-radio-button value="user">用户</el-radio-button>
            <el-radio-button value="nurse">陪诊师</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showFaceCollection = false">取消</el-button>
        <el-button type="primary" @click="startFaceCollection">开始采集</el-button>
      </template>
    </el-dialog>

    <!-- 人脸识别对话框 -->
     <el-dialog
        v-model="showFaceAuth"
        :title="faceAuthTitle"
        width="400px"
        center
        @close="stopRegisterCamera"
      >
        <div class="face-auth-content">
          <video ref="videoRef" width="320" height="240" autoplay></video>
          <canvas ref="canvasRef" style="display: none"></canvas>
          <div class="detection-tips">
            <el-icon v-if="detectionStatus === 'detecting'" color="#409EFF"><Loading /></el-icon>
            <span class="tip-text">
              {{ detectionTips }}
            </span>
          </div>
        </div>
        <template #footer>
          <el-button @click="showFaceAuth = false">取消</el-button>
          <el-button type="primary" @click="captureFace">开始识别</el-button>
        </template>
      </el-dialog>

    <!-- 添加注册对话框 -->
    <el-dialog
      v-model="showRegister"
      :title="registerDialogTitle"
      width="400px"
      center
      @close="handleRegisterClose">
      <el-form
        :model="registerForm"
        :rules="registerRules"
        ref="registerFormRef"
        label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名">
          </el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="registerForm.phone"
            placeholder="请输入手机号">
          </el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            show-password>
          </el-input>
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请确认密码"
            show-password>
          </el-input>
        </el-form-item>

        <!-- 陪护师特有字段 -->
        <template v-if="selectedRole === 'nurse'">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="registerForm.gender" placeholder="请选择性别">
              <el-option label="男" value="1" />
              <el-option label="女" value="0" />
            </el-select>
          </el-form-item>

          <el-form-item label="年龄" prop="age">
            <el-input v-model="registerForm.age" type="number" placeholder="请输入年龄"></el-input>
          </el-form-item>

          <el-form-item label="从业时间" prop="serviceYears">
            <el-input v-model="registerForm.serviceYears" type="number" placeholder="请输入从业时间（年）"></el-input>
          </el-form-item>

          <el-form-item label="工作简介" prop="biography">
            <el-input v-model="registerForm.biography" type="textarea" placeholder="请输入工作简介"></el-input>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <el-button @click="showRegister = false">取消</el-button>
        <el-button type="primary" @click="handleRegisterSubmit">确认注册</el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="showRegisterCamera"
      title="人脸采集"
      width="400px"
      center
      @close="stopRegisterCamera">
      <div class="face-auth-content">
        <video
          v-show="!registerPreviewImage"
          ref="registerVideoRef"
          width="320"
          height="240"
          autoplay
        ></video>
        <canvas ref="registerCanvasRef" style="display: none"></canvas>
      </div>

      <!-- 显示采集的人脸 -->
      <div class="face-preview">
        <img
          v-if="registerPreviewImage"
          :src="registerPreviewImage"
          alt="采集的人脸"
          class="preview-image"
        />
        <div v-else class="preview-placeholder">
          请先采集人脸图像
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <!-- 采集控制按钮 -->
          <template v-if="!registerPreviewImage">
            <el-button @click="showRegisterCamera = false">取消</el-button>
            <el-button
              type="primary"
              @click="captureFrame"
              :disabled="!registerVideoRef?.srcObject"
            >
              采集
            </el-button>
          </template>

          <!-- 确认/重新采集按钮 -->
          <template v-else>
            <el-button @click="retryCapture">重新采集</el-button>
            <el-button
              type="success"
              @click="confirmFaceCapture"
            >
              确认使用
            </el-button>
          </template>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// 修改后（正确示例）
import { ref, reactive, nextTick, computed, toRaw } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import {ip} from "@/router/ip.js";

const detectionStatus = ref('waiting');
const detectionTips = ref('请正对摄像头保持面部在框内');
const myRef = 'someValue';
const router = useRouter()
const selectedRole = ref('user')
const rolePlaceholder = computed(() => selectedRole.value === 'user' ? '用户名' : '陪诊师编号')
const loginForm = ref({
  username: '',
  password: ''
})
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
})
const loginFormRef = ref(null)
const rememberMe = ref(false)
const loading = ref(false)
const showFaceAuth = ref(false)
const faceAuthTitle = ref('人脸识别登录')
const videoRef = ref(null)
const canvasRef = ref(null)
const showRegister = ref(false)
const registerDialogTitle = ref('注册账号')
const registerForm = ref({
  username: '',
  phone: '',
  password: '',
  confirmPassword: '',
  gender: '',
  age: '',
  serviceYears: '',
  biography: ''
})
const registerRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (value !== registerForm.value.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }, trigger: 'blur' }
  ]
})
const registerFormRef = ref(null)
const showRegisterCamera = ref(false)
const registerVideoRef = ref(null)
const registerCanvasRef = ref(null)
const registerPreviewImage = ref('')
const isCapturing = ref(false);
const showFaceCollection = ref(false)
const faceCollectionForm = ref({
  username: '',
  password: ''
})
const faceCollectionRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
})
const faceCollectionFormRef = ref(null)

const goToRegister = () => {
  showRegister.value = true
}

// 封装获取摄像头流的函数
const getCameraStream = async () => {
  return await navigator.mediaDevices.getUserMedia({
    video: { width: 320, height: 240 }
  });
};

// 开始采集
const startFaceCollection = async () => {
  try {
    await faceCollectionFormRef.value.validate();

    // Get camera stream
    const stream = await navigator.mediaDevices.getUserMedia({
      video: { width: 320, height: 240 }
    }).catch(error => {
      if (error.name === 'NotAllowedError') {
        ElMessage.error('请允许访问摄像头以继续');
      } else if (error.name === 'NotFoundError') {
        ElMessage.error('未找到摄像头设备');
      } else if (error.name === 'NotReadableError') {
        ElMessage.error('摄像头不可用，请检查是否被其他应用占用');
      } else {
        ElMessage.error('无法访问摄像头: ' + error.message);
      }
      throw error; // Re-throw the error to stop further execution
    });

    if (registerVideoRef.value) {
      registerVideoRef.value.srcObject = stream;
      await registerVideoRef.value.play();
    }
    showRegisterCamera.value = true;
  } catch (error) {
    console.error('摄像头错误:', error);
  }
};

// 采集当前帧
const captureFrame = () => {
  const video = registerVideoRef.value;
  const canvas = registerCanvasRef.value;

  canvas.width = video.videoWidth;
  canvas.height = video.videoHeight;

  const ctx = canvas.getContext('2d');
  ctx.drawImage(video, 0, 0);

  registerPreviewImage.value = canvas.toDataURL('image/jpeg');
};

// 重新采集
const retryCapture = () => {
  registerPreviewImage.value = '';
  // 重新启动摄像头
  startFaceCollection();
};

// 确认采集
const confirmFaceCapture = async () => {
  if (!registerPreviewImage.value) {
    ElMessage.warning('请先采集人脸图像');
    return;
  }

   try {
    // 将响应式对象转换为原始对象
   const formData = toRaw(faceCollectionForm.value); // 使用 toRaw // 修改为 faceCollectionForm.value

    // 调用新接口
    const response = await axios.post(`http://${ip}:8000/api/face-collection`, {
      ...formData,
      role: selectedRole.value,
      image: registerPreviewImage.value
    });

    if (response.data.success) {
      ElMessage.success('人脸注册成功');
      showRegisterCamera.value = false;
      showFaceCollection.value = false;
    } else {
      ElMessage.error(response.data.error || '人脸注册失败');
    }
  } catch (error) {
    console.error('注册失败:', error);
    ElMessage.error(error.response?.data?.error || '服务器错误');
  } finally {
    stopRegisterCamera();
  }
};

// 停止摄像头
const stopRegisterCamera = () => {
  console.log('stopRegisterCamera 被调用'); // 添加日志
  if (registerVideoRef.value && registerVideoRef.value.srcObject) {
    const stream = registerVideoRef.value.srcObject;
    const tracks = stream.getTracks();
    tracks.forEach(track => {
      console.log('关闭 registerVideoRef 的 track:', track); // 添加日志
      track.stop();
    });
  }

  if (videoRef.value && videoRef.value.srcObject) {
    const stream = videoRef.value.srcObject;
    const tracks = stream.getTracks();
    tracks.forEach(track => {
      console.log('关闭 videoRef 的 track:', track); // 添加日志
      track.stop();
    });
  }
};


// 正确的方法定义（删除重复定义）
//前端增加活体检测
const startFaceAuth = async () => {
  try {
    // 检查设备是否有摄像头
    const devices = await navigator.mediaDevices.enumerateDevices();
    const hasCamera = devices.some(device => device.kind === 'videoinput');

    if (!hasCamera) {
      ElMessage.error('未检测到摄像头设备');
      return;
    }

    // 启动摄像头，使用更严格的约束
    const stream = await navigator.mediaDevices.getUserMedia({
      video: {
        width: 640,
        height: 480,
        facingMode: 'user' // 强制使用前置摄像头
      }
    });

    if (videoRef.value) {
      videoRef.value.srcObject = stream;
      await videoRef.value.play();
    }

    showFaceAuth.value = true;
  } catch (error) {
    ElMessage.error('无法访问摄像头');
    console.error('摄像头访问错误:', error);
  }
};



const handleRegisterSubmit = async () => {
  try {
    await registerFormRef.value.validate();
    // 添加 role 字段到请求体
    const requestData = {
      ...registerForm.value,
      role: selectedRole.value
    };
    const response = await axios.post(`http://${ip}:8000/api/register`, requestData);
    if (response.data.message === '注册成功') {
      ElMessage.success('注册成功');
      showRegister.value = false;
    } else {
      ElMessage.error('注册失败，请稍后再试');
    }
  } catch (error) {
    console.error('注册请求出错:', error);
    ElMessage.error('注册请求出错，请稍后再试');
  }
};

//登录后跳转路由
const routeMap = {
  user: '/',
  nurse: '/nurse'
};

//人脸识别登录
const handleFaceLogin = async (imageData) => {
  try {
    loading.value = true;
    const response = await axios.post(`http://${ip}:8000/api/login-face`, {
      image: imageData,
      role: selectedRole.value
    });

    if (response.data.success) {
      localStorage.setItem('userid', response.data.userid);
      localStorage.setItem('username', response.data.username);
      localStorage.setItem('role', response.data.role); // 存储用户角色
      localStorage.setItem('token', 'your_token_here'); // 确保设置 Token

      // 根据角色跳转
      const routeMap = {
        user: '/',
        nurse: '/nurse'
      };
      console.log('人脸登录跳转:', routeMap[response.data.role]);
      //router.replace(routeMap[response.data.role]);

      ElMessage.success('人脸登录成功');
      try {
        const targetRoute = routeMap[response.data.role];
        if (targetRoute) {
          await router.push(targetRoute);
        } else {
          console.error('未找到对应角色的路由');
          ElMessage.error('登录成功，但无法确定跳转页面');
        }
      } catch (error) {
        console.error('路由跳转出错:', error);
        ElMessage.error('路由跳转失败，请稍后再试');
      }
    } else {
      ElMessage.error(response.data.error || '人脸验证失败');
    }
  } catch (error) {
    ElMessage.error('人脸登录失败: ' + error.response?.data?.error);
  } finally {
    loading.value = false;
  }
};

//账号密码登录
const handleLogin = async () => {
    await loginFormRef.value.validate();
    loading.value = true;
    console.log(`http://${ip}:8000/api/login`, 'server')
    const response = await axios.post(`http://${ip}:8000/api/login`, loginForm.value);
    if (response.data.message === '登录成功') {
      const userData = response.data.rows[0];
      console.log('陪护师ID已存储:', userData)
      localStorage.setItem('userid', userData.userid);
      localStorage.setItem('role', userData.role); // 存储角色
      localStorage.setItem('token', 'your_token_here'); // 确保设置 Token
      // 如果角色是陪护师，保存陪护师ID
      if (userData.role === 'nurse') {
        const caregiverId = userData.associatedcaregiver
        if (!caregiverId) {
          ElMessage.error('未找到陪护师ID，请联系管理员')
        } else {
          localStorage.setItem('caregiverId', caregiverId) // 保存陪护师ID
          console.log('陪护师ID已存储:', caregiverId) // 添加日志
        }
      }

      // 根据角色跳转
      const routeMap = {
        user: '/',
        nurse: '/nurse'
      };
      console.log('跳转路由:', routeMap[userData.role]);
      router.replace(routeMap[userData.role]);

      ElMessage.success('登录成功');
      console.log('当前 localStorage:', localStorage);
    }
    loading.value = false;
};

// 修改人脸识别捕获方法
const captureFace = async () => {
  detectionStatus.value = 'detecting';
  detectionTips.value = '正在检测人脸...';

  // 添加延迟确保图像稳定
  await new Promise(resolve => setTimeout(resolve, 500));

  const video = videoRef.value;
  const canvas = canvasRef.value;

  // 确保画布尺寸正确
  canvas.width = video.videoWidth;
  canvas.height = video.videoHeight;

  // 绘制图像到画布
  const ctx = canvas.getContext('2d');
  ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

  // 获取Base64数据（带前缀）
  const imageData = canvas.toDataURL('image/jpeg');

  if (videoRef.value && videoRef.value.srcObject) {
            const stream = videoRef.value.srcObject;
            const tracks = stream.getTracks();
            tracks.forEach(track => track.stop());
        }

  // 关闭摄像头
  if (video.srcObject) {
    video.srcObject.getTracks().forEach(track => track.stop());
  }
  showFaceAuth.value = false;

  // 调用登录方法
  await handleFaceLogin(imageData);
};


const handleRegisterClose = () => {
  registerForm.value = {
    username: '',
    phone: '',
    password: '',
    confirmPassword: '',
    gender: '',
    age: '',
    serviceYears: '',
    biography: ''
  }
}
</script>


<style scoped lang="scss">
.login-container{
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh; /* 确保容器高度至少为视口高度 */
  justify-content: center;
  align-items: center;
  background-image: url('@/assets/beijing.jpg'); /* @ 是 src 目录的别名 */
  background-size: cover; /* 让背景图片覆盖整个容器 */
  background-position: center; /* 背景图片居中显示 */
  background-repeat: no-repeat; /* 背景图片不重复 */

  .login-card {
    width: 400px;
    padding: 20px;

    .login-header {
      text-align: center;
      margin-bottom: 30px;

      .logo {
        width: 80px;
        margin-bottom: 10px;
      }

      h2 {
        margin: 0;
        color: #303133;
        font-size: 24px;
      }
    }

    .login-form {
      .login-options {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
      }

      .login-button {
        width: 100%;
      }

      .face-login {
        margin-top: 20px;
        text-align: center;

        .el-button {
          margin-top: 15px;
        }
      }
    }
  }
}

.face-auth-content {
  display: flex;
  justify-content: center;

  video {
    border-radius: 4px;
  }
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  .right-options {
    display: flex;
    align-items: center;
    gap: 8px;
  }
}

.face-preview {
  text-align: center;
  margin-bottom: 10px;

  .preview-image {
    width: 160px;
    height: 120px;
    object-fit: cover;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    margin-bottom: 10px;
  }
}

.dialog-footer {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.role-select {
  margin-bottom: 30px;
  text-align: center;

  .el-radio-group {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }
}

// 修改单选按钮组的样式
:deep(.el-radio-button__inner) {
  &:hover {
    color: var(--el-color-primary);
  }
}

// 添加边框样式
:deep(.el-radio-button:first-child .el-radio-button__inner) {
  border-left: 1px solid var(--el-border-color);
}

:deep(.el-radio-button:last-child .el-radio-button__inner) {
  border-right: 1px solid var(--el-border-color);
}

.preview-placeholder {
  width: 320px;
  height: 240px;
  border: 2px dashed #ccc;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
}
</style>